package com.shujing.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shujing.mapper.ArticleMapper;
import com.shujing.pojo.Article;
import com.shujing.pojo.PageBean;
import com.shujing.service.ArticleService;
import com.shujing.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author 陈书憬
 * @version 1.0
 * 2024/4/9
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 该接口用于新增文章(发布文章)
     *
     * @param article
     * @return
     */
    @Override
    public void addArticle(Article article) {
        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        articleMapper.insert(article);
    }

    /**
     * 该接口用于根据条件查询文章,带分页
     *
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @param state
     * @return
     */
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 1.创建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        // 2.开启分页擦汗寻PageHelper
        PageHelper.startPage(pageNum, pageSize);

        // 3.调用mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId, categoryId, state);
        Page<Article> p = (Page<Article>) as;

        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    /**
     * 该接口用于根据ID获取文章详细信息
     *
     * @param id
     * @return
     */
    @Override
    public Article detail(Integer id) {

        return articleMapper.selectById(id);

    }

    /**
     * 该接口用于更新文章信息
     *
     * @param article
     * @return
     */
    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    /**
     * 该接口用于根据ID删除文章
     * @param id
     * @return
     */
    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
